package com.ruoyi.web.controller.net;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ftp.FtpUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.net.domain.*;
import com.ruoyi.net.netconf.Device;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.*;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.web.core.service.FtpService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-接口-模式配置Controller
 * 网管系统无去激活按钮！！！！
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-接口-模式配置")
@RestController
@RequestMapping("/element/port/mode")
public class ElementPortModeController extends BaseController {
    @Autowired
    private IElementPortModeService elementPortModeService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    @Autowired
    private IElementPortEthService portEthService;

    @Autowired
    private IElementPortMtnFgService portMtnFgService;

    @Autowired
    private FtpService ftpService;

    @ApiOperation(value = "FTP测试", httpMethod = "GET")
    @GetMapping("/ftp")
    public AjaxResult ftp(String remoteFilePath, String localFilePath ) {
        if (StringUtils.isEmpty(remoteFilePath)) {
            remoteFilePath = "/a/b/c/d.dat";
        }
        if (StringUtils.isEmpty(localFilePath)) {
            localFilePath = "/Users/yy/Downloads/abcd.dat";
        }
        ftpService.downloadFileFromFtp(remoteFilePath, localFilePath);
        return AjaxResult.success();
    }

    /**
     * 校时
     */
    @ApiOperation(value = "校时", httpMethod = "POST")
    @PostMapping("/time/{elementId}")
    public AjaxResult time(@PathVariable("elementId") String elementId) {
        NetElement netElement = netElementService.getCacheObject(elementId);

        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            // 手动设置系统时间
            deviceManager.executeRPC("<set-systime xmlns=\"http://fiberhome.com/fhnw/yang/systemmanage/fos-system-oper\">" +
                    "<date-time>" + DateUtils.getTime() + "</date-time>" +
                    "<type>LOCAL</type>" +
                    "</set-systime>");

            /*
            设置netconf 命令兼容模式 todo 2025-02-14 和小二沟通
             */
            deviceManager.editConfig("<ext-nms xmlns=\"http://fiberhome.com/fhnw/yang/fos-extension-nms\">" +
                    "        <netconf-ignore-unknown-node>" +
                    "          <enabled>enable</enabled>" +
                    "        </netconf-ignore-unknown-node>" +
                    "      </ext-nms>", "merge");
            return AjaxResult.success();
        }
        else {
            return AjaxResult.error("设备未连接, ip：" + netElement.getIp());
        }
    }

    /**
     * 读取网元-接口-模式配置列表
     */
    @ApiOperation(value = "读取网元-接口-模式配置列表 init", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:mode:list')")
    @GetMapping("/init")
    public AjaxResult init(ElementPortMode elementPortMode) {
        elementPortModeService.init(elementPortMode);
        return AjaxResult.success();
    }

    /**
     * 读取网元-接口-模式配置列表
     */
    @ApiOperation(value = "读取网元-接口-模式配置列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:mode:list')")
    @GetMapping("/read")
    public TableDataInfo read(ElementPortMode elementPortMode) {

        List<ElementPortMode> elementPortModes = new ArrayList<>();
        StringBuilder xml = new StringBuilder();
        xml.append(
                "<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                        "        <enabled>enable</enabled>" +
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
        NetElement netElement = netElementService.getCacheObject(elementPortMode.getElementId());
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            String rpcReply = deviceManager.getConfig(xml.toString());

            // 解析xml
            NodeList list = findNetConfXmlNodes(rpcReply, "//interfaces/interface");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementPortMode entity = new ElementPortMode();
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    String portType = getXmlLabelValue(node, "type");
                    entity.setPortName(getXmlLabelValue(node, "name"));
//                    entity.setPortMode(getXmlLabelValue(node, "enabled"));
                    entity.setStatus("1"); // 从设备读取到的配置，设置状态为激活
                    if (StringUtils.isNotEmpty(portType) && (portType.equalsIgnoreCase("eth-phy") || portType.equalsIgnoreCase("mtn-fgphy"))) {
                        entity.setPortMode((StringUtils.isNotEmpty(portType) && portType.startsWith("ETH")) ? "enable" : "disable");
                        elementPortModes.add(entity);
                    }
                }
            }
        }
        startPage();
        return getDIYPageTable(elementPortModes);
    }

    /**
     * 查询网元-接口-模式配置列表
     */
    @ApiOperation(value = "查询网元-接口-模式配置列表，读取设备比对入库并查询", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:mode:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementPortMode elementPortMode) {
        startPage();
        List<ElementPortMode> list = elementPortModeService.selectElementPortModeListOnly(elementPortMode);
        return getDataTable(list);
    }

    /**
     * 导出网元-接口-模式配置列表
     */
    @ApiOperation(value = "导出网元-接口-模式配置列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:mode:export')")
    @Log(title = "网元-接口-模式配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementPortMode elementPortMode) {
        List<ElementPortMode> list = elementPortModeService.selectElementPortModeListOnly(elementPortMode);
        ExcelUtil<ElementPortMode> util = new ExcelUtil<ElementPortMode>(ElementPortMode.class);
        util.exportExcel(response, list, "网元-接口-模式配置数据");
    }

    /**
     * 获取网元-接口-模式配置详细信息
     */
    @ApiOperation(value = "获取网元-接口-模式配置详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:mode:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementPortModeService.selectElementPortModeById(id));
    }

    /**
     * 新增网元-接口-模式配置
     */
    @ApiOperation(value = "新增网元-接口-模式配置", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:mode:add')")
    @Log(title = "网元-接口-模式配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementPortMode elementPortMode) {
        return toAjax(elementPortModeService.insertElementPortMode(elementPortMode));
    }

    /**
     * 修改网元-接口-模式配置
     */
    @ApiOperation(value = "修改网元-接口-模式配置", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:mode:edit')")
    @Log(title = "网元-接口-模式配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementPortMode elementPortMode) {
        return toAjax(elementPortModeService.updateElementPortMode(elementPortMode));
    }

    /**
     * 删除网元-接口-模式配置
     */
    @ApiOperation(value = "删除网元-接口-模式配置", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:mode:remove')")
    @Log(title = "网元-接口-模式配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementPortModeService.deleteElementPortModeByIds(ids));
    }

    /**
     * 刷新
     */
    @ApiOperation(value = "刷新", httpMethod = "GET")
    @GetMapping(value = "/refresh/{ip}")
    public AjaxResult refresh(@PathVariable("ip") String ip) {
        // TODO: 2024/12/8 从设备获取 接口信息

        Device device = deviceManager.getDevice(ip);
        if (device.isConnected()) {
            StringBuilder xml = new StringBuilder();
            xml.append("<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                    "    <interfaces>" +
                    "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                    "        <type>ETH-PHY</type>" +
                    "      </interface>" +
                    "    </interfaces>" +
                    "  </if>");
            String rpcReply = deviceManager.getConfig(xml.toString());
            // 解析xml，如果接口名称存在，批量更新条目状态为 激活
            /*List<String> list = findNetConfXmlNodes(rpcReply, "//interfaces/interface/name");
            if (!StringUtils.isEmpty(list)) {
                elementPortModeService.updateElementPortModeStatus(list.toArray(new String[]{}), "1");
            }*/
        }
        return AjaxResult.success();
    }

    /**
     * 刷新--TEST
     */
    @ApiOperation(value = "刷新--TEST", httpMethod = "GET")
    @GetMapping(value = "/refresh/test/{status}")
    public AjaxResult refreshTest(@PathVariable("status") String status) {
        List<String> list = new ArrayList<>();
        list.add("eth-1gi0/1/0/2");
        list.add("eth-1gi0/1/0/3");
        if (!StringUtils.isEmpty(list)) {
            elementPortModeService.updateElementPortModeStatus(list.toArray(new String[]{}), status);
        }
        return AjaxResult.success();
    }

    /**
     * 激活设备
     *
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementPortMode elementPortMode = elementPortModeService.selectElementPortModeById(id);
        elementPortMode.setStatus("1");
        if (this.sendXml(elementPortMode)) {
            return toAjax(elementPortModeService.updateElementPortMode(elementPortMode));
        } else {
            return AjaxResult.error("激活失败");
        }
    }

    /**
     * 去激活设备
     *
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementPortMode elementPortMode = elementPortModeService.selectElementPortModeById(id);
        elementPortMode.setStatus("0");
        if (this.sendXml(elementPortMode)) {
            return toAjax(elementPortModeService.updateElementPortMode(elementPortMode));
        } else {
            return AjaxResult.error("去激活失败");
        }
    }

    /*<device xmlns="http://fiberhome.com/fhnw/devicemanager/fos-device">
    <ethmode-cfgs>
      <ethmode-cfg>
        <if-name>0/6/0/1</if-name>
        <enable>disable</enable>
      </ethmode-cfg>
    </ethmode-cfgs>
  </device>*/

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementPortMode entity) {
        boolean isSend = true;
        NetElement netElement = netElementService.getCacheObject(entity.getElementId());
        StringBuilder xml = new StringBuilder();
        // 查找
        int portIndex = StringUtils.indexOfAny(entity.getPortName(), "/");
        xml.append("<device xmlns=\"http://fiberhome.com/fhnw/devicemanager/fos-device\">" +
                "    <ethmode-cfgs>" +
                "      <ethmode-cfg>" +
                "        <if-name>" + entity.getPortName().substring(portIndex - 1) + "</if-name>" +
                "        <enable>" + entity.getPortMode() + "</enable>" +
                "      </ethmode-cfg>" +
                "    </ethmode-cfgs>" +
                "  </device>");
        // 判断是否可取修改模式
        ElementPortEth elementPortEth = new ElementPortEth();
        elementPortEth.setElementId(entity.getElementId());
//        elementPortEth.setStatus("1");
        elementPortEth.setPortName(entity.getPortName().substring(portIndex - 1));
        List<ElementPortEth> portEths = portEthService.selectElementPortEthList(elementPortEth);
        if (portEths != null && !portEths.isEmpty() && "1".equals(portEths.get(0).getStatus()) &&  "enable".equalsIgnoreCase(entity.getPortMode())) {
            // 已激活，无法修改模式
            return false;
        }
        ElementPortMtnFg elementPortMtnFg = new ElementPortMtnFg();
        elementPortMtnFg.setElementId(entity.getElementId());
//        elementPortMtnFg.setStatus("1");
        elementPortMtnFg.setTerminalName(entity.getPortName().substring(portIndex - 1));
        List<ElementPortMtnFg> portMtnFgs = portMtnFgService.selectElementPortMtnFgList(elementPortMtnFg);
        if (portMtnFgs != null && !portMtnFgs.isEmpty() && "1".equals(portMtnFgs.get(0).getStatus()) &&  "disable".equalsIgnoreCase(entity.getPortMode())) {
            // 已激活，无法修改模式
            return false;
        }
        // 设备联调，2025-02-06通过验收
        Device device =  deviceManager.getDevice(netElement.getIp());
        logger.info("接口模式配置xml：{}", xml);
        if (device.isConnected()) {
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }
        if (isSend) {
            updateETHorMTN(entity, portEths, portMtnFgs);
        }
        return isSend;
    }

    /**
     * 更新ETH以太主接口和MTN-PHY
     * @param entity
     */
    private void updateETHorMTN(ElementPortMode entity, List<ElementPortEth> portEths, List<ElementPortMtnFg> portMtnFgs) {

        // 新增
        if ("enable".equalsIgnoreCase(entity.getPortMode())) {
            // 删除 MTN-fg接口
            if (portMtnFgs != null && !portMtnFgs.isEmpty()) {
                portMtnFgService.deleteElementPortMtnFgById(portMtnFgs.get(0).getId());
            }
            ElementPortEth elementPortEth = new ElementPortEth();
            elementPortEth.setElementId(entity.getElementId());
            // ETH以太主接口
            if (portEths == null || portEths.isEmpty()) {
                elementPortEth.setId(IdUtils.simpleUUID());
                elementPortEth.setPortName(entity.getPortName());
                elementPortEth.setTerminalName(entity.getPortName());
                elementPortEth.setElementId(entity.getElementId());
                elementPortEth.setStatus("0");
                portEthService.insertElementPortEth(elementPortEth);
            }
            else {
                elementPortEth.setId(portEths.get(0).getId());
                elementPortEth.setPortName(entity.getPortName());
                elementPortEth.setTerminalName(entity.getPortName());
                elementPortEth.setElementId(entity.getElementId());
                elementPortEth.setStatus("0");
                portEthService.updateElementPortEth(elementPortEth);
            }
        } else {
            // 删除 ETH以太主接口
            if (portEths != null && !portEths.isEmpty()) {
                portEthService.deleteElementPortEthById(portEths.get(0).getId());
            }
            ElementPortMtnFg elementPortMtnFg = new ElementPortMtnFg();
            elementPortMtnFg.setElementId(entity.getElementId());
            // MTN-fg接口
            if (portMtnFgs == null || portMtnFgs.isEmpty()) {
                elementPortMtnFg.setId(IdUtils.simpleUUID());
                elementPortMtnFg.setTerminalName(entity.getPortName());
                elementPortMtnFg.setElementId(entity.getElementId());
                elementPortMtnFg.setStatus("0");
                portMtnFgService.insertElementPortMtnFg(elementPortMtnFg);
            }
            else {
                elementPortMtnFg.setId(portMtnFgs.get(0).getId());
                elementPortMtnFg.setTerminalName(entity.getPortName());
                elementPortMtnFg.setElementId(entity.getElementId());
                elementPortMtnFg.setStatus("0");
                portMtnFgService.updateElementPortMtnFg(elementPortMtnFg);
            }
        }
    }
}